package cn.kk.communication.utils;
/*
 *@author KK on 2022.09.11 21:13
 */

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DBUtils {
    private static DruidDataSource ds = null;
    private static final ThreadLocal<Connection>  THREAD_LOCAL = new ThreadLocal<>();
    static {
        Properties properties = new Properties();
        try {
            properties.load(DBUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取资源的方法
    public static DruidDataSource getDataSource(){
        return ds;
    }

    //获取连接的方法
    public static Connection getConnection(){
        Connection conn = null;
        try {
            conn = THREAD_LOCAL.get();
            if (conn==null) {
                conn = ds.getConnection();
                THREAD_LOCAL.set(conn);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    //关闭资源
    public static void closeAll(AutoCloseable...parmas) {
        for (AutoCloseable parma : parmas) {
            try {
                parma.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
